﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GONES.IBLL;
using GONES.IDAL;
using GONES.Model;
using log4net;
using System.Reflection;
using GONES.Tools.Common;
using Newtonsoft.Json;

namespace GONES.BLL
{
    public class S_NavManager : IS_NavManager
    {
        public IS_NavDao s_NavDao;
        protected static readonly ILog Log =
             LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        public IS_LogDao S_LogDao;
        private readonly IUserInfo _userInfo;
        public S_LogManager S_LogManager;

        public S_NavManager(IUserInfo userinfo)
        {
            _userInfo = userinfo;
        }

        public string ErrMsg { get; set; }

        public S_Nav Get(string id)
        {
            return s_NavDao.Get(id);
        }

        public void Add(S_Nav nav)
        {
            if (IsError(nav))
                return;
            nav.CreateTime = System.DateTime.Now;
            s_NavDao.Save(nav);
            SaveLog("菜单管理", "菜单添加", "系统管理", nav);
   
        }

        public void Edit(S_Nav nav)
        {
           if(IsError(nav))
               return ;
           nav.ModifyTime = System.DateTime.Now;
            s_NavDao.Update(nav);
            SaveLog("菜单管理", "菜单修改", "系统管理", nav);
        }

        public void Delete(string id)
        {
            S_Nav nav = s_NavDao.Get(id);
            s_NavDao.Delete(nav);
            SaveLog("菜单管理", "菜单删除","系统管理",nav );
        }


        public IList<S_Nav> GetNavListByUserId(string UserId)
        {
            string hql = string.Format(@"from S_Nav e where e.ID in(select t.NavId from S_UserNavpermission s,S_NavPermission t where s.NavPermissionId = t.ID and s.Uid='{0}') order by e.SortNum", UserId);
            return s_NavDao.GetHqlList(hql);
        }

        public IList<S_Nav> GetParentNavListByUserId(string UserId)
        {
            string hql = string.Format(@"FROM S_Nav e where e.ID =(
select DISTINCT a.Parentid FROM S_Nav a where a.ID in(
select t.NavId from S_UserNavpermission s,S_NavPermission t  where s.NavPermissionId = t.ID and s.Uid='{0}'))", UserId);
            return s_NavDao.GetHqlList(hql);
        }

        /// <summary>
        /// 获取指定菜单下的子菜单个数
        /// </summary>
        /// <param name="parentid">父菜单ID</param>
        /// <returns>菜单数</returns>
        public int GetNavCountByParentId(string parentid)
        {
            return s_NavDao.GetHqlList(string.Format("select e from S_Nav e where 1=1 and e. Parentid='{0}'", parentid)).Count;
        }

        public IList<S_Nav> List(IList<DataFilter> filters)
        {
            string strFilter = DataOperate.GetHqlstrByExtFilter(filters, "e");
            string hql = "SELECT e FROM S_Nav e  where  1=1 " +
                                       (string.IsNullOrEmpty(strFilter) ? string.Empty : " and " + strFilter) +
                                       " ORDER BY e.ID DESC";

            return s_NavDao.GetHqlList(hql);
        }

        public IList<S_Nav> NavList(IList<DataFilter> filters, int pageindex, int pagesize, ref long recordcount)
        {
            string strFilter = DataOperate.GetHqlstrByExtFilter(filters, "e");

             recordcount = s_NavDao.ExecHqlResultLong("SELECT COUNT(*) FROM S_Nav e where " +
                                               (string.IsNullOrEmpty(strFilter) ? string.Empty : " and " + strFilter));

            return s_NavDao.GetHqlList("SELECT e FROM S_Nav e  where  " +
                                       (string.IsNullOrEmpty(strFilter) ? string.Empty : " and " + strFilter) +
                                       " ORDER BY e.ID DESC", (pageindex - 1) * pagesize,
                                       pagesize);
        }

        private void SaveLog(string module, string operate, string logtype, S_Nav nav)
        {
            S_LogManager = new S_LogManager(_userInfo);
            string detail = string.Format("{0}:菜单名称是{1}，菜单地址是{2}", operate, nav.Title, nav.Url);
            SaveLog(module, operate, logtype, detail);
            if (Log.IsInfoEnabled)
                Log.Info(string.Format("{0}：{1}", operate, JsonConvert.SerializeObject(nav)));
        }

        protected bool IsError(S_Nav nav)
        {
            if (string.IsNullOrEmpty(nav.Title))
            {
                ErrMsg = "导航标题不能为空！";
            }
            if (string.IsNullOrEmpty(nav.Url))
            {
                ErrMsg = "导航地址不能为空！";
            }
            if (!string.IsNullOrEmpty(ErrMsg))
                return true;
            return false;
        }

        /// <summary>
        /// 保存日志
        /// </summary>
        /// <param name="module">模块名称</param>
        /// <param name="operate">操作名称</param>
        /// <param name="logtype">日志类型（系统管理、基础资料等）</param>
        /// <param name="detail">详细日志</param>
        protected void SaveLog(string module, string operate, string logtype, string detail)
        {
            try
            {
                S_LogDao.Save(new S_Log
                {
                    ID = Rnd.Guid.ToString(),
                    Module = module,
                    Operate = operate,
                    Detail = detail,
                    LogType = logtype,
                    OpDate = DateTime.Now,
                    CreateUser = _userInfo.CLoginInfo.UserName,
                    CreateTime = DateTime.Now,
                    ModifyUser = _userInfo.CLoginInfo.UserName,
                    ModifyTime = DateTime.Now,
                    Ip = Tools.Common.Tools.GetIP()
                });
            }
            catch
            {
            }
        }
    }
}
